/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.component;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
 * 说明：
 * 图片显示面板，会自动按比例缩放图片
 * @Author：李智深
 * @Date：2012-03-14
 */
public class JPanelComponent extends JPanel{
	private static final long serialVersionUID = 1L;
	private Image im;
	public JPanelComponent(Image im,int x,int y){
		this.im=im;
		this.setSize(x, y);
		this.setMaximumSize(new Dimension(x, y));
		this.setMinimumSize(new Dimension(x, y));
		this.setPreferredSize(new Dimension(x, y));
		this.setBorder(BorderFactory.createEtchedBorder());//设置边框
	}
	
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		if(im!=null){
			int pWidth = this.getWidth();
			int pHeight = this.getHeight();
			int mWidth = im.getWidth(null);
			int mHeight = im.getHeight(null);
			int x, y;
			int width, height;
			if ((mWidth <= pWidth) && (mHeight <= pHeight)) {
				x = (pWidth - mWidth) / 2;
				y = (pHeight - mHeight) / 2;
				width = mWidth;
				height = mHeight;
			} else {
				width = pWidth;
				height = pHeight;
				float widthScale = (float) pWidth / (float) mWidth;

				float heightScale = (float) pHeight / (float) mHeight;
				if (widthScale < heightScale)
					height = (int) (mHeight * widthScale);
				else
					width = (int) (mWidth * heightScale);
				x = (pWidth - width) / 2;
				y = (pHeight - height) / 2;
			}
			g.clearRect(0, 0, pWidth, pHeight);
			g.drawImage(im, x, y, width, height, this);
//			g.dispose();
		}
	}

	public void setImagePath(String imagePath) {
		if(imagePath!=null){
			this.im = new ImageIcon(imagePath).getImage();
			this.repaint();
		} else {
			im = null;
		}
	}
	
	public void setImage(String strPath) {
		if (strPath == null || strPath.length() == 0 )
			return;
		File file = new File(strPath);
			try {
				im = ImageIO.read(file);
			} catch (IOException e) {
//				e.printStackTrace();
			}
		if (im == null) {
			JOptionPane.showMessageDialog(null, "请确认图片文件"+strPath+"是图片且还存在！");
			return;
		}
		this.repaint();
	}
}
